package com.fq.web.controller;

import com.fq.client.service.UserService;
import com.fq.web.convertor.UserConverter;
import com.fq.web.domain.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author jifang
 * @since 15/12/16 下午7:57.
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService service;

    @RequestMapping("/generate_user.do")
    public ModelAndView register(String name, String password) {
        Integer id = service.generate(name, password);
        return new ModelAndView("add_user", "user", new UserVO(id, name, password));
    }

    @RequestMapping("/users.do")
    public ModelAndView users() {
        List<UserVO> users = UserConverter.convert(service.getAllUsers());
        return new ModelAndView("users", "users", users);
    }

    @RequestMapping("/delete.do")
    public ModelAndView delete(Integer id){
        service.removeUserById(id);
        return users();
    }

    @RequestMapping("/login.do")
    public void login(HttpServletRequest request, HttpServletResponse response, String name, String password) throws IOException, ServletException {
        String path = request.getContextPath();
        String redirect;
        if (name.equals("admin") && password.equals("admin")) {
            response.addCookie(new Cookie("admin", "admin"));
            redirect = String.format("%s/dashboard.jsp", path);
        } else {
            redirect = String.format("%s/index.jsp", path);
        }

        response.sendRedirect(redirect);
    }
}